package com.padgett.resourcemanagement.service;

import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Text;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.appengine.labs.repackaged.org.json.JSONObject;
import com.padgett.resourcemanagement.data.ClientDAO;
import com.padgett.resourcemanagement.util.DateUtil;

/**
 * Get Business Client including all services and invoices.
 * 
 * @author andyleung
 * 
 */
@SuppressWarnings("serial")
public class AjaxGetServiceServlet extends HttpServlet{
	private static final Logger logger=Logger.getLogger(AjaxGetServiceServlet.class.getName());
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {
		String serviceId=req.getParameter("serviceId");
		Key key=KeyFactory.stringToKey(serviceId);
		Entity entity=ClientDAO.loadEntity(key);
		JSONObject service=new JSONObject();
		String response="";
		try {
			service.put("serviceId", KeyFactory.keyToString(entity.getKey()));
			Iterator<Entry<String, Object>> propertyIterator=entity.getProperties().entrySet().iterator();
			while(propertyIterator.hasNext()){
				Map.Entry<String, Object> entry=(Map.Entry<String, Object>)propertyIterator.next();
				String entryKey=entry.getKey();
				if(entry.getValue() instanceof Text){
					service.put(entryKey, ((Text)entry.getValue()).getValue());
				}else if(entry.getValue() instanceof Date){
					Date date=(Date)entry.getValue();
					service.put(entryKey, DateUtil.formatDate(date, DateUtil.LONG_DATE_FORMAT));
				}else{
					service.put(entryKey, entry.getValue());
				}
				if(entryKey.equalsIgnoreCase("accountant")&&entry.getValue()!=null){
					// Get Accountant nickname
					Key accountantKey=new KeyFactory.Builder("User",(String)entry.getValue()).getKey();
					Entity accountant=ClientDAO.loadEntity(accountantKey);
					if(accountant!=null){
						service.put("AccountantName",accountant.getProperty("Nickname"));
					}
				}
			}
			JSONObject responseObject=new JSONObject();
			responseObject.put("success", true);
			responseObject.put("data",service);
			response=responseObject.toString();
		} catch (JSONException e) {
			logger.severe(e.getMessage());
			e.printStackTrace();
			response="{\"success\":false,\"error\":\""+e.getMessage()+"\"}";
		}
		resp.getWriter().write(response);
	}
}
